import { formatRequestParams } from "@/utils";
import { PaginationProps } from "antd/lib/pagination";
import { useEffect } from "react";
import { useImmer } from "use-immer";
interface UseMyTable {
  service: (params?: any) => Promise<any>;
  initParams?: CustomParams;
  format?: boolean
}

export const useMyTable = ({ service, initParams = {}, format = true }: UseMyTable) => {
  const [state, setState] = useImmer({
    dataSource: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
    },
    loading: false,
    searchParams: {},
    options: [],
  });

  const getTableList = async (params?: any) => {
    setState((state) => {
      state.loading = true;
    });
    const [err, res] = await service(
      format ? formatRequestParams({ ...initParams, ...params }) : { ...initParams, ...params }
    );

    setState((state) => {
      state.loading = false;
      if (err) return;
      const {
        data: { content, totalElements, options },
      } = res;
      state.dataSource = content;
      state.pagination.total = totalElements;
      state.options = options;
    });
  };
  useEffect(() => {
    getTableList({
      page: state.pagination.current,
      pageSize: state.pagination.pageSize,
    });
  }, []);

  const turnPage: PaginationProps["onChange"] = (pageNumber, pageSize) => {
    setState((state) => {
      state.pagination.current = pageNumber;
      state.pagination.pageSize = pageSize;
    });
    getTableList({
      page: pageNumber,
      pageSize: pageSize,
      ...state.searchParams,
    });
  };

  const pagination: PaginationProps = {
    showQuickJumper: true,
    showSizeChanger: true,
    onChange: turnPage,
    showTotal(total, range) {
      if (range[1] === range[0]) {
        return `第${range[0]}条/总共${total}条`;
      } else {
        return `第${range[0]}-${range[1]}条/总共${total}条`;
      }
    },
    ...state.pagination,
  };

  const search = (params: any) => {
    setState((state) => {
      state.pagination.current = 1;
      state.searchParams = params;
    });
    getTableList({ ...params, page: 1, pageSize: state.pagination.pageSize });
  };

  const refresh = () => {
    getTableList({
      page: state.pagination.current,
      pageSize: state.pagination.pageSize,
      ...state.searchParams,
    });
  };
  return { ...state, pagination, search, refresh };
};
